# -*- coding: utf-8 -*-
'''
Created on Mar 27, 2013

@author: LONG HOANG GIANG
'''
import os, sys
import traceback
sys.path.append(os.path.join(os.path.dirname(__file__), '../'))
import pyLib
import sqlite3 as sqlite
import json
import datetime

def convertscheme(database):
    try:
        connection = sqlite.connect(database)
        cursor = connection.cursor()
        cursor.execute('''SELECT tbl_name FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence';''')
        val = cursor.fetchall()
        for v in val:
            table = v[0]
            if table.startswith('udv_'):
                cursor.execute("ALTER TABLE {0} RENAME TO vn_gq_{0}".format(table))
        cursor.close()
        connection.commit()
        connection.close()
    except:
        traceback.print_exc()
    return

def convertv3(database, output):
    if not output.endswith("/"): output += '/'
    filesOutputFolder = output + 'files/'
    if not os.path.isdir(filesOutputFolder):
        os.makedirs(filesOutputFolder, 0777)
    convertscheme(database)
    connection = sqlite.connect(database)
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM vn_gq_udv_category")
    categories = cursor.fetchall()
    if len(categories) > 0:
        acat = []
        for cat in categories:
            catName = cat[1]
            catId = cat[0]
            print catId, catName
            cursor.execute("SELECT * FROM vn_gq_udv_story WHERE catId=?", [catId])
            stories = cursor.fetchall()
            chapter = []
            for story in stories:
                print story[2].encode('utf-8')
                title = story[2].encode('utf-8')
                detail = story[3]
                fileId = pyLib.crc32unsigned("{0}-{1}".format(story[0].encode('utf-8'), title))
                filename = "{0}{1}".format(filesOutputFolder, fileId)
                pyLib.gzip(filename, json.dumps(detail))
                chapter.append({'title': title, 'id': fileId})
            chapterId = pyLib.crc32unsigned("{0}-{1}".format(catId, catName))
            pyLib.gzip("{0}{1}".format(filesOutputFolder, chapterId), json.dumps(chapter))
            acat.append({'name': catName, 'path': chapterId})
        pyLib.gzip(output + 'data', pyLib.encryptCipher(json.dumps(acat)))
    else:
        cursor.execute("SELECT * FROM vn_gq_udv_story")
        stories = cursor.fetchall()
        chapter = []
        for story in stories:
            print story[2].encode('utf-8')
            title = story[2].encode('utf-8')
            detail = story[3]
            fileId = pyLib.crc32unsigned("{0}-{1}".format(story[0], title))
            filename = "{0}{1}".format(filesOutputFolder, fileId)
            pyLib.gzip(filename, json.dumps(detail))
            chapter.append({'name': title, 'path': fileId})
        pyLib.gzip(output + 'data', pyLib.encryptCipher(json.dumps(chapter)))
    cursor.close()
    connection.close()
        
    
    
if __name__ == '__main__':
    
    name = raw_input("> Enter database in /longhoanggiang/database/?: ")
    if os.path.exists("/longhoanggiang/database/{0}".format(name)):
        print '\n> Start process /longhoanggiang/database/{0} to /longhoanggiang/truyentext/{0}'.format(name)
        convertv3("/longhoanggiang/database/{0}".format(name), "/longhoanggiang/truyentext/{0}".format(name))
    else:
        print "\n> This file not exist!"
    print '> Finished at {0}'.format(datetime.datetime.now())
    os._exit(1)
    